<html>
  <head>
    <script type="text/javascript">
      var origin = "*"; // Will be replaced with real origin
      var QUEUE = [];
      var QUEUE_RUNNING = false;
      async function sendtophone(how, value, value2) {
        if (how == 'blocks') {
          await sendblocks(value);
        } else if (how == 'version') {
          let resp = await getversion();
          window.opener.postMessage(resp, origin);
        } else if (how == 'asset') {
          // console.log("About to PUT " + value);
          let resp = await fetch('/?' + value, {
            method : 'PUT',
            mode: 'cors',
            body: value2 });
          let result = await resp.text();
          // console.log("Asset Result = " + result);
        } else if (how == 'extensions') {
          let resp = await
          fetch('/_extensions', {
            method: 'POST',
            mode: 'cors',
            body: value });
          let result = await resp.text();
          // Tell App Inventor that extensions are loaded
          window.opener.postMessage({'status' : 'EXTENSIONS_LOADED'},
                                    origin);
          // console.log("Extensions Result = " + result);
        }
      };
      async function sendblocks(block) {
        let resp = await fetch('/_newblocks', {
          method : 'POST',
          mode: 'cors',
          body: block });
        let data = await resp.json();
        // console.log(data);
        console.log('sendblocks: Response: ' + JSON.stringify(data));
        window.opener.postMessage(data, origin);
      }
      async function getversion() {
        let resp = await
        fetch('/_getversion');
        let data = await resp.json();
        // console.log(data);
        return data;
      }
      async function init() {
        // First let replmgr.js that we are loaded and running
        window.opener.postMessage({ "status" : "hello" }, origin);
        while (true) {
          // console.log('getting values');
          let resp = await fetch('/_values', {
            method: 'POST',
            mode: 'cors',
            cache: 'no-store',
            body: "IGNORED=STUFF" });
          let data = await resp.json();
          console.log("values: " + JSON.stringify(data));
          window.opener.postMessage(data, origin);
        }
      }
      function dowork() {
        let work = QUEUE.shift();
        if (!work) {
          // console.log("QUEUE_RUNNING = false");
          QUEUE_RUNNING = false;
        } else {
          origin = work.origin;
          let how = work.data[0];
          let value = work.data[1];
          let value2 = work.data[2];
          // console.log("About to: how = " + how + " value = " + value);
          sendtophone(how, value, value2).then(function() {
            setTimeout(() => {
              dowork();
            });
          });
        }
      };
      window.addEventListener("message", (event) => {
        QUEUE.push(event);
        if (!QUEUE_RUNNING) {
          QUEUE_RUNNING = true;
          // console.log("QUEUE_RUNNING = true");
          setTimeout(() => {
            dowork();
          });
        }
      });
      function closeme() {
        window.resizeTo(1, 1);
        window.moveTo(0, 0);
      }
      window.onload = init;
    </script>
  </head>
  <body>
    <img src="" style="width:180px; height:40px"/>
    <h1>This is a special window used by MIT App Inventor</h1>
    <p>
      You can safely ignore this window, it should close when you
      disconnect the MIT AI2 Companion, or exit MIT App Inventor.
    </p>
    <p>
      <button onClick="closeme();">Press this button</button>
      which will move this window to the upper left hand corner of
      your screen. You can then just click on the main window and
      continue working.
    </p>
  </body>
</html>
